package com.dingding.aop;

import cn.hutool.core.io.IoUtil;
import cn.hutool.extra.servlet.ServletUtil;
import cn.hutool.json.JSONUtil;
import com.auth0.jwt.exceptions.AlgorithmMismatchException;
import com.auth0.jwt.exceptions.SignatureVerificationException;
import com.auth0.jwt.exceptions.TokenExpiredException;
import com.dingding.common.Constants;
import com.dingding.common.TokenException;
import com.dingding.entity.UserSession;
import com.dingding.enums.ResponseCode;
import com.dingding.service.JwtService;
import com.dingding.service.RedisService;
import com.dingding.utils.SessionUserUtil;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpMethod;
import org.springframework.http.MediaType;
import org.springframework.stereotype.Component;
import org.springframework.util.CollectionUtils;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.BufferedReader;
import java.util.Map;
import java.util.Objects;

@Slf4j
@Component
public class JWTInterceptor implements HandlerInterceptor {

    @Autowired
    private RedisService redisService;

    @Autowired
    private JwtService jwtService;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        printRequestInfo(request);

        if (request.getMethod().equalsIgnoreCase(HttpMethod.OPTIONS.name())) {
            return true;
        }

        String token = request.getHeader("token");
        if (StringUtils.isBlank(token)) {
            token = request.getParameter("token");
        }
        if (StringUtils.isBlank(token)) {
            throw new TokenException(ResponseCode.TOKEN_EXPIRE.getCode(), "token不能为空");
        }

        try {
            JwtService.verify(token);
        } catch (SignatureVerificationException e) {
            log.error("无效签名！ 错误 ->", e);
            throw new TokenException(ResponseCode.TOKEN_EXPIRE.getCode(), "无效签名");
        } catch (TokenExpiredException e) {
            log.error("token过期！ 错误 ->", e);
            throw new TokenException(ResponseCode.TOKEN_EXPIRE.getCode(), "token过期");
        } catch (AlgorithmMismatchException e) {
            log.error("token算法不一致！ 错误 ->", e);
            throw new TokenException(ResponseCode.TOKEN_EXPIRE.getCode(), "token算法不一致");
        } catch (Exception e) {
            log.error("token无效！ 错误 ->", e);
            throw new TokenException(ResponseCode.TOKEN_EXPIRE.getCode(), "token无效");
        }

        UserSession user = jwtService.getUser(token);
        Object value = redisService.getValue(String.format(Constants.REDIS_KEY_TOKEN, user.getUserId()));
        if(Objects.isNull(value)) {
            log.error("token过期！");
            throw new TokenException(ResponseCode.TOKEN_EXPIRE.getCode(), "token过期");
        } else if (!token.equals(value.toString())) {
            log.error("token无效！");
            throw new TokenException(ResponseCode.TOKEN_EXPIRE.getCode(), "token无效");
        }

        SessionUserUtil.set(user);
        return true;
    }

//    @Override
//    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
//        User user = userMapper.selectById(2);
//        UserVo vo = new UserVo();
//        BeanUtils.copyProperties(user, vo);
//        UserUtil.set(vo);
//        return true;
//    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        SessionUserUtil.remove();
    }

    private void printRequestInfo(HttpServletRequest request) throws Exception {
        String url = request.getMethod() + " " + ServletUtil.getClientIP(request) + request.getRequestURI();

        // 打印请求参数
        if (isJsonRequest(request)) {
            String jsonParam = "";
            if (request instanceof XssHttpServletRequestWrapper) {
                BufferedReader reader = request.getReader();
                jsonParam = IoUtil.read(reader);
            }
            log.info("[PLUS]开始请求 => URL[{}],参数类型[json],参数:[{}]", url, jsonParam);
        } else {
            Map<String, String[]> parameterMap = request.getParameterMap();
            if (!CollectionUtils.isEmpty(parameterMap)) {
                String parameters = JSONUtil.toJsonStr(parameterMap);
                log.info("[PLUS]开始请求 => URL[{}],参数类型[param],参数:[{}]", url, parameters);
            } else {
                log.info("[PLUS]开始请求 => URL[{}],无参数", url);
            }
        }
    }

    /**
     * 判断本次请求的数据类型是否为json
     *
     * @param request request
     * @return boolean
     */
    private boolean isJsonRequest(HttpServletRequest request) {
        String contentType = request.getContentType();
        if (contentType != null) {
            return StringUtils.startsWithIgnoreCase(contentType, MediaType.APPLICATION_JSON_VALUE);
        }
        return false;
    }
}
